﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KaiXin.BLL.Interface;
using HtmlAgilityPack;
using KaiXin.DTO.Tycoon;
using KaiXin.DAL.XML;
using System.Text.RegularExpressions;

namespace KaiXin.BLL.Tycoon
{
    public class Tycoon:Robot,ITycoon
    {
        public Tycoon(string e, string p) : base(e, p) { }

        #region private
        /// <summary>
        /// 将个人现金的中文转成数字
        /// </summary>
        /// <param name="price">e.g. 50万2380、1亿561万</param>
        /// <returns></returns>
        private double String2Double(string price)
        {
            int y = price.IndexOf("亿");
            int w = price.IndexOf("万");
            if (w==-1)
            {
                return double.Parse(price);
            }
            else if(y==-1)
            {
                return double.Parse(price.Replace("万", ".")) * 10000;
            }
            else
            {
                int t = int.Parse(price.Substring(0, y));
                int t2 = int.Parse(price.Substring(y + 1, w-y-1));
                return (t * 100000000 + t2 * 10000);
            }
        }

        #endregion

        #region ITycoon 成员

        public HtmlDocument Buy(Goods goods)
        {
            string buy_url = "http://www.kaixin001.com/!rich/!purchase.php?iid={0}&purchase_price={1}&num={2}";
            int count = (int)(GetMyMoney() / goods.CurrentPrice);
            if (count > 0)
            {
                count = count > 20 ? 20 : count;
                Log.WriteLog(string.Format("委托买入：{0}   买入价格:{1}    买入时间:{2}", goods.Name, goods.CurrentPrice, DateTime.Now), "c:\\Commission.txt");
                return AccessPage(string.Format(buy_url, goods.ID, goods.CurrentPrice, count));
            }
            return null;
        }

        public HtmlDocument Sell(Goods goods)
        {
            string sell_url = "http://www.kaixin001.com/!rich/!sell.php?iid={0}&cost_price={3}&sell_price={1}&num={2}";
            Log.WriteLog(string.Format("委托卖出：{0}   卖出价格:{1}    卖出时间:{2}", goods.Name, goods.CurrentPrice, DateTime.Now), "c:\\Commission.txt");
            //goods.MinPrice 为买入价格从GetMyGoods()里获取goods
            return AccessPage(string.Format(sell_url, goods.ID, goods.CurrentPrice, goods.Count, goods.MinPrice));

        }

        public double GetMyMoney()
        {
            HtmlDocument doc = AccessPage("http://www.kaixin001.com/!rich/index.php");
            HtmlNode nodeMoney = doc.DocumentNode.SelectSingleNode("id('zcsum')/li[1]/b");
            string money = nodeMoney.InnerText.Substring(nodeMoney.InnerText.IndexOf("：") + 1).Replace("元", "");
            return String2Double(money);
        }

        public List<Goods> GetMyGoods()
        {
            HtmlDocument doc = AccessPage("http://www.kaixin001.com/!rich/myitem.php");

            List<Goods> list = new List<Goods>();
            HtmlNodeCollection nc = doc.DocumentNode.SelectNodes("//div[@class='list_zc']/ul");
            if (nc != null)
            {
                foreach (var item in nc)
                {

                    Goods goods = new Goods();
                    HtmlNode liNode = item.SelectSingleNode("./li[2]");
                    goods.Name = liNode.SelectSingleNode("./b").InnerText;
                    goods.Count = int.Parse(Regex.Replace(liNode.InnerText, @"[^\d]*", string.Empty));
                    goods.ID = liNode.InnerText;
                    HtmlNode aNode = item.SelectSingleNode("./li[7]/a[1]");
                    string href = aNode.Attributes["href"].Value;
                    int s = href.IndexOf("(") + 1;
                    int e = href.IndexOf(")");
                    string[] temp = href.Substring(s, e - s).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    goods.ID = temp[0];
                    goods.CurrentPrice = long.Parse(temp[2].Replace("'", string.Empty));//卖出价格
                    goods.MinPrice = long.Parse(temp[1]);//买入价格
                    list.Add(goods);
                }

            }
            return list;
        }

        #endregion
    }
}
